const app = require("express")();
const client = require("prom-client");

const defaultLabels = { serviceName: "node-api" };
client.register.setDefaultLabels(defaultLabels);

// 计数器
const counter = new client.Counter({
  name: "counter",
  help: "请求次数",
});
// 仪表值(与计数器类型，但是值可以减少)
const gauge = new client.Gauge({
  name: "gauge",
  help: "仪表值",
});
// 柱状图
const histogram = new client.Histogram({
  name: "histogram",
  help: "柱状图",
  buckets: [0.1, 5, 15, 50, 100, 500],
});
// 汇总
const summary = new client.Summary({
  name: "summary",
  help: "汇总",
});

app.get("/", async (req, res) => {
  counter.inc();

  // 网络请求时间
  const endForGauge = gauge.startTimer();

  // histogram计算请求持续时间
  const endForHistogram = histogram.startTimer();

  // 汇总
  const endForSummary = summary.startTimer();

  const millisec = Math.ceil(Math.random() * 3 * 1000); // 生成 1-3000 秒之间的数字
  await new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log(`延时 ${millisec / 1000} 秒`);
      resolve();
    }, millisec);
  });

  endForGauge();
  const seconds = endForHistogram();
  endForSummary();
  console.log(`请求持续 ${seconds} 秒`);

  res.json("Hello World!");
});

let scrapeTimes = 0;
app.get("/metrics", (req, res) => {
  console.log(`====== 第 ${scrapeTimes++} 次抓取数据 ======\n`);
  console.log(client.register.metrics());
  res.end(client.register.metrics());
});

app.listen(9095, () => {
  console.log(`\n * 🚀 服务启动成功!\n`);
});
